#include "InteropService.h"
#include "platform.h"

#include <stdexcept>
#include <string>
#include <sstream>
using namespace std;


#define NCP_SCHEMA		1
#define NCP_USER		2
#define NCP_LOCALE		3
#define NCP_CONNECTION	4
//#define NCP_PORT		5

extern "C" __declspec(dllexport) int QueryEnv(int kind, wchar_t* buffer, size_t length);
//extern "C" __declspec(dllexport) int UpdateEnv(int kind, const wchar_t* buffer, size_t length);

IContext* InteropService::s_instance = nullptr;
InteropService::InteropService(void)
{
}
InteropService::~InteropService(void)
{
}
void InteropService::set(IContext* cx)
{
	// TODO: consider concurrency
	if(!cx)
	{
		throw runtime_error("Invalid pointer of IContext");
	}
	s_instance = cx;
}
IContext& InteropService::get()
{
	if(!s_instance)
	{
		throw runtime_error("Pointer of IContext is null");
	}
	return *s_instance;
}

int QueryEnv(int kind, wchar_t* buffer, size_t length)
{
	switch (kind)
	{
	case NCP_SCHEMA:
		{
			wcscpy_s(
				buffer,
				length,
				InteropService::get().GetCompany().c_str());
			return 0;
		}
	case NCP_USER:
		{
			wcscpy_s(
				buffer,
				length,
				InteropService::get().GetUser().c_str());
			return 0;
		}
	case NCP_LOCALE:
		{
			wcscpy_s(
				buffer,
				length,
				InteropService::get().GetLocale().c_str());
			return 0;
		}
	case NCP_CONNECTION:
		{
			wcscpy_s(
				buffer,
				length,
				InteropService::get().GetTanantConnection().c_str());
			return 0;
		}
	default:
		return 1;
	}
}
//int UpdateEnv(int kind, const wchar_t* buffer, size_t length)
//{
//	switch (kind)
//	{
//	case NCP_PORT:
//		{
//			unsigned short port;
//			wstringstream ss;
//			ss << buffer;
//			ss >> port;
//
//#undef SetPort
//			InteropService::get().SetPort(port);
//			return 0;
//		}
//	default:
//		return 1;
//	}
//}